package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.api.services.TerminalApiService;
import com.molichuxing.gateway.bff.terminal.entity.request.modify.DeviceModifyVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceAppVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceErrorListVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceErrorVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceListVo;
import com.molichuxing.gateway.bff.terminal.services.TerminalBffService;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 终端相关接口
 *
 * @author zhaopenghui
 * @date 2020年4月1日
 */
@Api(tags = "终端相关接口")
@RestController
@RequestMapping(value = "/terminal")
public class TerminalApiServiceImpl extends RootApiService implements TerminalApiService {
    private static final Logger logger = LoggerFactory.getLogger(TerminalApiServiceImpl.class);

    @Resource
    TerminalBffService terminalBffService;


    @Override
    @ApiOperation(value = "获取设备管理列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "onlineStatus", value = "在线状态（0：全部，1：在线，2：离线）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "cpu", value = "cpu", required = false, dataType = "String"),
            @ApiImplicitParam(name = "storeId", value = "门店ID", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "terminalVersionCode", value = "设备类型（01:第一代，02:第二代，03：第三代）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startNetTime", value = "入网时间（开始）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endNetTime", value = "入网时间（结束）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "startLastConnectTime", value = "最后通讯时间（开始）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endLastConnectTime", value = "最后通讯时间（结束）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/device/list")
    public ResponseResult<Paged<DeviceListVo>> getDevicePage(@RequestParam Map<String, Object> params,
                                                             @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<DeviceListVo>> result = new ResponseResult<>();
        try {
            Object startNetTime = params.get("startNetTime");
            Object endNetTime = params.get("endNetTime");
            if (startNetTime != null) {
                LocalDateTime dayStart = ObjectCastUtil.getDayStart(startNetTime);
                params.put("startNetTime", dayStart);
            }
            if (endNetTime != null) {
                LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endNetTime);
                params.put("endNetTime", dayEnd);
            }

            return result.success(terminalBffService.getDevicePage(params, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getDevicePage]获取终端列表信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDevicePage]获取终端列表信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getDevicePage]获取终端列表信息异常", e);
            result.error("获取终端列表信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取故障监控列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cpu", value = "cpu", required = false, dataType = "String"),
            @ApiImplicitParam(name = "storeId", value = "门店ID", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "status", value = "状态（0：异常，1：正常）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/device/error/list")
    public ResponseResult<Paged<DeviceErrorListVo>> getDeviceErrorPage(@RequestParam Map<String, Object> params,
                                                                       @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<DeviceErrorListVo>> result = new ResponseResult<>();
        try {
            Integer dealerId = RequestAttrUtil.getCurrentDealerId();
            params.put("dealerId", dealerId);
            return result.success(terminalBffService.getDeviceErrorPage(params, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getDeviceErrorPage]获取故障监控列表信息", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDeviceErrorPage]获取故障监控列表信息", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getDeviceErrorPage]获取故障监控列表信息", e);
            result.error("获取故障监控列表信息");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "编辑设备")
    @PostMapping(value = "/device/modify")
    public ResponseResult<Boolean> modifyDevice(@RequestBody DeviceModifyVo deviceModifyVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(terminalBffService.modifyDevice(deviceModifyVo));
        } catch (IllegalArgumentException e) {
            logger.error("[modifyDevice]编辑设备异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[modifyDevice]编辑设备异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyDevice]编辑设备异常 ", e);
            result.error("编辑设备异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取资源状况")
    @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, dataType = "Integer")
    @GetMapping(value = "/device/app/list")
    public ResponseResult<List<DeviceAppVo>> getDeviceAppList(@RequestParam Integer deviceId) {
        ResponseResult<List<DeviceAppVo>> result = new ResponseResult<>();
        try {
            return result.success(terminalBffService.getDeviceAppList(deviceId));
        } catch (IllegalArgumentException e) {
            logger.error("[getDeviceAppList]获取资源状况异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDeviceAppList]获取资源状况异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getDeviceAppList]获取资源状况异常 ", e);
            result.error("获取资源状况异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "获取故障详情")
    @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, dataType = "Integer")
    @GetMapping(value = "/device/error/detail")
    public ResponseResult<DeviceErrorVo> getDeviceError(@RequestParam Integer deviceId) {
        ResponseResult<DeviceErrorVo> result = new ResponseResult<>();
        try {
            return result.success(terminalBffService.getDeviceError(deviceId));
        } catch (IllegalArgumentException e) {
            logger.error("[getDeviceError]获取故障详情异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getDeviceError]获取故障详情异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getDeviceError]获取故障详情异常 ", e);
            result.error("获取故障详情异常");
        }
        return result;
    }


}
